<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\HelpRequest;
use Illuminate\Http\Request;

class HelpRequestController extends Controller
{
    /**
     * 获取求助请求列表
     */
    public function index(Request $request)
    {
        try {
            $query = HelpRequest::with(['user'])
                ->where('is_hidden', false);

            // 筛选条件
            if ($request->has('status')) {
                $query->where('status', $request->status);
            }

            $requests = $query->orderBy('created_at', 'desc')->paginate(20);

            return response()->json([
                'success' => true,
                'data' => [
                    'current_page' => $requests->currentPage(),
                    'data' => $requests->items(),
                    'last_page' => $requests->lastPage(),
                    'total' => $requests->total(),
                    'per_page' => $requests->perPage(),
                    'from' => $requests->firstItem(),
                    'to' => $requests->lastItem()
                ],
                'message' => '获取求助列表成功',
                'timestamp' => now()->toISOString()
            ]);
            
        } catch (\Exception $e) {
            \Log::error('HelpRequestController@index error: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'error' => [
                    'message' => '获取求助列表失败',
                    'details' => $e->getMessage()
                ]
            ], 500);
        }
    }

    /**
     * 创建新的求助请求
     */
    public function store(Request $request)
    {
        try {
            $request->validate([
                'title' => 'required|string|max:200',
                'description' => 'required|string|max:2000',
                'is_urgent' => 'boolean',
                'is_anonymous' => 'boolean'
            ]);

            $helpRequest = HelpRequest::create([
                'user_id' => auth()->id(),
                'title' => $request->title,
                'description' => $request->description,
                'is_urgent' => $request->get('is_urgent', false),
                'is_anonymous' => $request->get('is_anonymous', false),
                'status' => 'open',
                'is_hidden' => false
            ]);

            $helpRequest->load('user');

            return $this->success($helpRequest, '求助请求创建成功', 201);
        } catch (\Exception $e) {
            \Log::error('创建求助请求失败: ' . $e->getMessage());
            return $this->error('创建求助请求失败', 500);
        }
    }
}